{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/nceder/qpb4e/blob/main/code/Chapter%2007/Chapter_07.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 7 Dictionaries\n",
        "\n",
        "# 7.1 What is a dictionary?"
      ],
      "metadata": {
        "id": "g4SuseG8oEJz"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bmrKckaI6KJM"
      },
      "source": [
        "x = []\n",
        "y = {}\n",
        "\n",
        "y[0] = 'Hello'\n",
        "y[1] = 'Goodbye'"
      ],
      "execution_count": 1,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "hpsN-liD6KJJ",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        },
        "outputId": "e01c6cde-244a-428b-ce65-604601e1a6c0"
      },
      "source": [
        "x[0] = 'Hello'"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "error",
          "ename": "IndexError",
          "evalue": "list assignment index out of range",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mIndexError\u001b[0m                                Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-2-12433aff2248>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'Hello'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;31mIndexError\u001b[0m: list assignment index out of range"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "g_psKVJV6KJN",
        "outputId": "1da5a6b1-df09-47c1-85d3-e334c94ea5f0",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "print(y[0])\n",
        "print(y[1] + \", Friend.\")"
      ],
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Hello\n",
            "Goodbye, Friend.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gvduM_-P6KJO",
        "outputId": "7f766db0-6c00-4781-c327-7669f8f092f8",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "y['greeting'] = \"Bon jour\"\n",
        "y['farewell'] = \"Adios\"\n",
        "print(y['greeting'])\n",
        "print(y['farewell'] + \", Friend.\")"
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Bon jour\n",
            "Adios, Friend.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xO12xRBQ6KJP",
        "outputId": "ec2cf869-1190-4ea9-f7fe-ac6034f90153",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "english_to_french = {}                     #A\n",
        "english_to_french['red'] = 'rouge'         #B\n",
        "english_to_french['blue'] = 'bleu'\n",
        "english_to_french['green'] = 'vert'\n",
        "print(\"red is\", english_to_french['red'])  #C"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "red is rouge\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Try This: Create a dictionary\n",
        "Write the code to ask the user for three names and three ages. After the names and ages are entered, ask the user for one of the names, and print the correct age.\n"
      ],
      "metadata": {
        "id": "k0gLTodNILnX"
      }
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "C5ca_i40IfIu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "name_age = {}\n",
        "for i in range(3):\n",
        "    name = input(\"Name? \")\n",
        "    age = int(input(\"Age? \"))\n",
        "    name_age[name] = age\n",
        "\n",
        "name_choice = input(\"Name to find? \")\n",
        "print(name_age[name_choice])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "fwsj15luIQhe",
        "outputId": "a11ca358-901e-4c7d-d513-f4e345297b95"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Name? Tom\n",
            "Age? 33\n",
            "Name? Talita\n",
            "Age? 28\n",
            "Name? Rania\n",
            "Age? 32\n",
            "Name to find? Tom\n",
            "33\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 7.2 Other dictionary operations"
      ],
      "metadata": {
        "id": "0fr2fNTbovtq"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6cf2cmDZ6KJQ"
      },
      "source": [
        "english_to_french = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}"
      ],
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "c-1FPauo6KJQ",
        "outputId": "5910542e-45df-4061-b514-8647faae45c6",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "len(english_to_french)"
      ],
      "execution_count": 8,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "3"
            ]
          },
          "metadata": {},
          "execution_count": 8
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "uCvTsCL96KJR",
        "outputId": "63a02803-72ae-4d71-fba5-aef7d633cd97",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "list(english_to_french.keys())"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['red', 'blue', 'green']"
            ]
          },
          "metadata": {},
          "execution_count": 9
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "It2SBpN96KJR",
        "outputId": "fa3629e1-a863-46da-a6fa-666b03a3f4aa",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "list(english_to_french.values())"
      ],
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['rouge', 'bleu', 'vert']"
            ]
          },
          "metadata": {},
          "execution_count": 10
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "E35zaejy6KJS",
        "outputId": "c50d9dbc-3530-4157-9238-ff81581cc596",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "list(english_to_french.items())"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[('red', 'rouge'), ('blue', 'bleu'), ('green', 'vert')]"
            ]
          },
          "metadata": {},
          "execution_count": 11
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "XGfYnTUo6KJS",
        "outputId": "c5989129-d6c3-47c9-c752-5e93f27a0919",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "list(english_to_french.items())"
      ],
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[('red', 'rouge'), ('blue', 'bleu'), ('green', 'vert')]"
            ]
          },
          "metadata": {},
          "execution_count": 12
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "WCfDhoUk6KJS",
        "outputId": "9499f7f6-e9ef-45ed-fe54-b5ddabf2b2ae",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "del english_to_french['green']\n",
        "list(english_to_french.items())"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[('red', 'rouge'), ('blue', 'bleu')]"
            ]
          },
          "metadata": {},
          "execution_count": 13
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2LCf5kiE6KJS",
        "outputId": "d6c237eb-19e1-4ae1-a085-c5a2b3c0f850",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "'red' in english_to_french"
      ],
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {},
          "execution_count": 14
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "oljR9PR_6KJS",
        "outputId": "b273bac9-44a2-4524-c552-b826fa0a6dd9",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "'orange' in english_to_french"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "False"
            ]
          },
          "metadata": {},
          "execution_count": 15
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yWzbV_Uc6KJS",
        "outputId": "50a74c3f-7f12-4b74-92f7-c200e959d9a1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "print(english_to_french.get('blue', 'No translation'))"
      ],
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "bleu\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1kmbaDvc6KJT",
        "outputId": "59eb0da1-5618-47d1-eec2-820d9ed54139",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "print(english_to_french.get('chartreuse', 'No translation'))"
      ],
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "No translation\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "CnYJFDmE6KJT",
        "outputId": "dff3ec15-d8a9-4744-8f65-c9f197d16cb3",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "print(english_to_french.setdefault('chartreuse', 'No translation'))"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "No translation\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "sXjgWlMP6KJT",
        "outputId": "571f7183-0427-4c23-a676-7e7919686bd4",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "x = {0: 'zero', 1: 'one'}\n",
        "y = x.copy()\n",
        "y"
      ],
      "execution_count": 19,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{0: 'zero', 1: 'one'}"
            ]
          },
          "metadata": {},
          "execution_count": 19
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iSzTNJmW6KJT",
        "outputId": "798219f1-bfd9-4c88-d587-127dc035c3c7",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "z = {1: 'One', 2: 'Two'}\n",
        "x = {0: 'zero', 1: 'one'}\n",
        "x.update(z)\n",
        "x"
      ],
      "execution_count": 20,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{0: 'zero', 1: 'One', 2: 'Two'}"
            ]
          },
          "metadata": {},
          "execution_count": 20
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Quick Check: Dictionary operations\n",
        "Assume that you have a dictionary `x = {'a':1, 'b':2, 'c':3, 'd':4}` and a dictionary `y = {'a':6, 'e':5, 'f':6}`. What would be the contents of x after the following snippets of code have executed?:\n",
        "```\n",
        "del x['d']\n",
        "z = x.setdefault('g', 7)\n",
        "x.update(y)\n",
        "```"
      ],
      "metadata": {
        "id": "Psd33Kq3prFw"
      }
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "rjRTMlN2psDu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "x = {'a':1, 'b':2, 'c':3, 'd':4}\n",
        "y = {'a':6, 'e':5, 'f':6}\n",
        "\n",
        "del x['d']\n",
        "print(x)"
      ],
      "metadata": {
        "id": "U8xK65YipsNB",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "z = x.setdefault('g', 7)\n",
        "print(x)"
      ],
      "metadata": {
        "id": "lHbk4eMUqYP6",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title\n",
        "x.update(y)\n",
        "print(x)"
      ],
      "metadata": {
        "id": "KVr06rMtqfoP",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 7.3 Word Counting"
      ],
      "metadata": {
        "id": "JfDXqsJupsVe"
      }
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "GCnzYevE6KJT",
        "outputId": "85d14e05-5b71-48da-816e-5921268d79c9",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "sample_string = \"To be or not to be\"\n",
        "occurrences = {}\n",
        "for word in sample_string.split():\n",
        "    occurrences[word] = occurrences.get(word, 0) + 1    #A\n",
        "\n",
        "for word in occurrences:\n",
        "    print(\"The word\", word, \"occurs\", occurrences[word],\n",
        "           \"times in the string\")"
      ],
      "execution_count": 22,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The word To occurs 1 times in the string\n",
            "The word be occurs 2 times in the string\n",
            "The word or occurs 1 times in the string\n",
            "The word not occurs 1 times in the string\n",
            "The word to occurs 1 times in the string\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 7.4 What can be used as a key?"
      ],
      "metadata": {
        "id": "8b_70pDJrLc6"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Quick Check: What can be a key?\n",
        "Decide which of the following expressions can be a dictionary key:\n",
        "\n",
        "`1; 'bob'; ('tom', [1, 2, 3]); [\"filename\"]; \"filename\"; (\"filename\",  \"extension\") `\n"
      ],
      "metadata": {
        "id": "eeT9ZfoWrQJt"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 7.5 Sparse matrices"
      ],
      "metadata": {
        "id": "lRHXpWZbrkJC"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "matrix = [[3, 0, -2, 11], [0, 9, 0, 0], [0, 7, 0, 0], [0, 0, 0, -5]]\n",
        "rownum = 0\n",
        "colnum = 1\n",
        "element = matrix[rownum][colnum]"
      ],
      "metadata": {
        "id": "ZkJGYvae7OEZ"
      },
      "execution_count": 26,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "matrix = {(0, 0): 3, (0, 2): -2, (0, 3): 11,\n",
        "          (1, 1): 9, (2, 1): 7, (3, 3): -5}\n",
        "if (rownum, colnum) in matrix:\n",
        "    element = matrix[(rownum, colnum)]\n",
        "else:\n",
        "    element = 0\n",
        "element = matrix.get((rownum, colnum), 0)"
      ],
      "metadata": {
        "id": "TsXU00Ev7d0D"
      },
      "execution_count": 27,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "matrix = {(0, 0): 3, (0, 2): -2, (0, 3): 11,\n",
        "          (1, 1): 9, (2, 1): 7, (3, 3): -5}\n",
        "if (rownum, colnum) in matrix:\n",
        "    element = matrix[(rownum, colnum)]\n",
        "else:\n",
        "    element = 0\n",
        "element = matrix.get((rownum, colnum), 0)"
      ],
      "metadata": {
        "id": "GxVQ681Q7hGY"
      },
      "execution_count": 28,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 7.6 Dictionaries as caches"
      ],
      "metadata": {
        "id": "GQHOlmlirtnm"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Try This: Using dictionaries\n",
        "Suppose that you're writing a program that works like a spreadsheet. How might you use a dictionary to store the contents of a sheet? Write some sample code to both store a value and retrieve a value in a particular cell. What might be some drawbacks to this approach?\n",
        "\n",
        "You could use tuples of row, column values as keys to store the values in a dictionary. One drawback would be that the keys wouldn’t be sorted, so you’d have to manage that situation as you grabbed the keys/values to render as a spreadsheet.\n",
        "\n"
      ],
      "metadata": {
        "id": "GwzD0VPMr3Rg"
      }
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "tUGfsR0lQ1A_"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "sheet = {}\n",
        "sheet[('A', 1)] = 100\n",
        "sheet[('B', 1)] = 1000\n",
        "\n",
        "print(sheet[('A', 1)])\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "aqihiqLnI8Gv",
        "outputId": "da51e9ea-89a3-448f-e3d0-c44a5c1dc317"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "100\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 7.8 Lab 7: Word counting\n",
        "\n",
        "In the previous lab, you took the text of the first chapter of Moby Dick, normalized the case, removed punctuation, and wrote the separated words to a file. In this lab, we will use the file created in chapter 6 to count the number of times each word occurs.\n",
        "\n",
        "To do this we will read the file, and use a dictionary as described above to count the occurrences, using the words as the keys and the number of occurrences as the values. Once we have processed the file, we’ll print out the five most common and five least common words and the number of times they occur.\n",
        "To open and read the file we can use code that’s similar to what we used the last time, but we won’t need an output file:\n",
        "```with open(\"moby_01_clean.txt\", \"r\") as infile:\n",
        "    for word in infile:\n",
        "        # use stip() method to remove any extra whitespace\n",
        "        # increase the count for current word\n",
        "```\n",
        "In addition to using a dictionary to count occurrences, you'll need to use the `items()`1 method to get the keys and values as a series of tuples that you can sort. For this you may need to refer to the chapter on lists.\n"
      ],
      "metadata": {
        "id": "5ESyYoRlRC73"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Run the cell below to get the file moby_01_clean.txt"
      ],
      "metadata": {
        "id": "HEgBC0JaKcCQ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!wget https://raw.githubusercontent.com/nceder/qpb4e/main/code/Chapter%2007/moby_01_clean.txt  &> null  && echo Downloaded"
      ],
      "metadata": {
        "id": "j6F1x_g-ry2j",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f906a9b9-f51a-40d9-f4e4-b4ce560254d3"
      },
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Downloaded\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Create your solution in this cell\n",
        "\n"
      ],
      "metadata": {
        "id": "cwOxy0p4Rg2T"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Solution created by the author\n",
        "\n",
        "word_count = {}\n",
        "with open(\"moby_01_clean.txt\", \"r\") as infile:\n",
        "    for word in infile:\n",
        "        # use strip() method to remove any extra whitespace\n",
        "        word = word.strip()\n",
        "\n",
        "        # increase the count for current word\n",
        "        count = word_count.setdefault(word, 0)\n",
        "        count += 1\n",
        "        word_count[word] += 1\n",
        "\n",
        "word_list = list(word_count.items())\n",
        "word_list.sort(key=lambda x: x[1])\n",
        "print(\"Most common words:\")\n",
        "for word in reversed(word_list[-5:]):\n",
        "    print(word)\n",
        "print(\"\\nLeast common words:\")\n",
        "for word in word_list[:5]:\n",
        "    print(word)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "vbJ72kc4I86t",
        "outputId": "dfaa9e7c-8f9a-41ce-99c5-1c6e7121d131"
      },
      "execution_count": 30,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Most common words:\n",
            "('the', 14)\n",
            "('i', 9)\n",
            "('and', 9)\n",
            "('of', 8)\n",
            "('is', 7)\n",
            "\n",
            "Least common words:\n",
            "('call', 1)\n",
            "('ishmael', 1)\n",
            "('years', 1)\n",
            "('ago', 1)\n",
            "('never', 1)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Generated by Colaboratory\n",
        "\n",
        "# prompt: Open the file moby_01_clean.txt and use a dictionary to count the\n",
        "#         occurrences of each word. Do not use a Counter. Print the five\n",
        "#         most common words and their number of occurrences. Print the\n",
        "#         five least common words and their number of occurrences.\n",
        "\n",
        "# Open the file and read the text into a variable.\n",
        "with open('moby_01_clean.txt', 'r') as f:\n",
        "  text = f.read()\n",
        "\n",
        "# Split the text into words.\n",
        "words = text.split()\n",
        "\n",
        "# Create a dictionary to count the occurrences of each word.\n",
        "word_counts = {}\n",
        "for word in words:\n",
        "  if word not in word_counts:\n",
        "    word_counts[word] = 0\n",
        "  word_counts[word] += 1\n",
        "\n",
        "# Find the five most common words and their number of occurrences.\n",
        "most_common = sorted(word_counts.items(), key=lambda item: item[1], reverse=True)[:5]\n",
        "\n",
        "# Find the five least common words and their number of occurrences.\n",
        "least_common = sorted(word_counts.items(), key=lambda item: item[1])[:5]\n",
        "\n",
        "# Print the results.\n",
        "print(\"Most common words:\")\n",
        "for word, count in most_common:\n",
        "  print(f\"{word}: {count}\")\n",
        "\n",
        "print(\"\\nLeast common words:\")\n",
        "for word, count in least_common:\n",
        "  print(f\"{word}: {count}\")\n"
      ],
      "metadata": {
        "id": "nd5u9IQQJ3YH"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Generated by Copilot\n",
        "\n",
        "# Open the file\n",
        "with open('moby_01_clean.txt', 'r') as file:\n",
        "    # Read the file content\n",
        "    content = file.read()\n",
        "\n",
        "# Split the content into words\n",
        "words = content.split()\n",
        "\n",
        "# Count the occurrences of each word using a dictionary\n",
        "word_counts = {}\n",
        "for word in words:\n",
        "    if word in word_counts:\n",
        "        word_counts[word] += 1\n",
        "    else:\n",
        "        word_counts[word] = 1\n",
        "\n",
        "# Sort the word counts in descending order\n",
        "sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)\n",
        "\n",
        "# Print the five most common words and their occurrences\n",
        "print(\"Five most common words:\")\n",
        "for word, count in sorted_word_counts[:5]:\n",
        "    print(f\"{word}: {count}\")\n",
        "\n",
        "# Print the five least common words and their occurrences\n",
        "print(\"Five least common words:\")\n",
        "for word, count in sorted_word_counts[-5:]:\n",
        "    print(f\"{word}: {count}\")"
      ],
      "metadata": {
        "id": "MDVXTVqzhhDJ"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}